package com.itboye.eweilisten.me.home;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;

import com.itboye.eweilisten.R;
import com.itboye.eweilisten.adapter.ParentAdapter;
import com.itboye.eweilisten.app.MyApplication;
import com.itboye.eweilisten.base.BaseActivity;
import com.itboye.eweilisten.me.login.LoginActivity;
import com.itboye.eweilisten.me.timu.ZongHeActivity;
import com.itboye.eweilisten.model.GoodsDetailBean;
import com.itboye.eweilisten.presenter.UserPresenter;
import com.itboye.eweilisten.util.loadingutil.MAlert;
import com.itboye.eweilisten.util.sputil.Const;
import com.itboye.eweilisten.util.sputil.SPUtils;
import com.itboye.eweilisten.util.widget.IsStringSPUtils;
import com.itboye.eweilisten.util.widget.XImageLoader;
import com.itboye.eweilisten.volley.ResultEntity;

import java.text.SimpleDateFormat;
import java.util.Observable;
import java.util.Observer;

/**
 * Created by itboye on 2017/3/11.
 * 立即体验
 */
public class ActivityExperience extends BaseActivity implements ExpandableListView.OnGroupExpandListener,
        ParentAdapter.OnChildTreeViewClickListener, Observer {
    private ExpandableListView listView;
    private Context mContext;
//    private ArrayList<ParentEntity> parents;


    private ParentAdapter adapter;
    GoodsDetailBean bean;
    UserPresenter presenter;
    private TextView tvOrderTitle;//标题
    private TextView tvMath;//月份
    private TextView tvpriceOrder;//价格/每一个
    private TextView tvCha;//biaoti
    private TextView tvExName;//共计多少
    private ImageView imgBook;//图片
    private TextView tvTitle;
    private TextView tvcment;
    String countment;
    String price;
    String name;
    String id;
    String imgid;
    private ImageView back;
    String uid;
    boolean bought;

    TextView validTime,carefullyBuy;

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.activity_experience);
        bought = getIntent().getBooleanExtra("bought", false);
        listView = (ExpandableListView) findViewById(R.id.list);
        mContext = this;
        presenter = new UserPresenter(this);
        uid = (String) SPUtils.get(MyApplication.instance, null, Const.ID, "");
        bean = new GoodsDetailBean();
        countment = getIntent().getStringExtra("countment");
        price = getIntent().getStringExtra("price");
        name = getIntent().getStringExtra("name");
        id = getIntent().getStringExtra("id");
        imgid = getIntent().getStringExtra("imgid");
        tvcment.setText(countment);
        tvExName.setText(name);
        presenter.onGoodsInfoLie(id, IsStringSPUtils.IsUid(),IsStringSPUtils.getSid());
        XImageLoader.load(Const.IMAGE_HEAD + imgid, imgBook);
        showProgressDialog("数据加载中...", true);
        tvTitle.setText("微测试目录");
        if(bought) {
            carefullyBuy=(TextView)findViewById(R.id.tv_carefully_buy);
            validTime=(TextView)findViewById(R.id.tv_validtime);
            carefullyBuy.setVisibility(View.GONE);
            validTime.setVisibility(View.VISIBLE);
        }
        //登录的广播
        IntentFilter filter = new IntentFilter(LoginActivity.LOGIN);
        registerReceiver(loginReceiver, filter);
        //网络广播
        IntentFilter connect_recover = new IntentFilter("connect_recover");
        registerReceiver(netBroadcastReceiver,connect_recover);
    }

    BroadcastReceiver loginReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            uid = (String) SPUtils.get(MyApplication.instance, null, Const.ID, "");
        }
    };

    BroadcastReceiver netBroadcastReceiver= new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals("connect_recover")&&intent.getIntExtra("recover",0)==400){
                presenter.onGoodsInfoLie(id, IsStringSPUtils.IsUid(),IsStringSPUtils.getSid());
            }
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(loginReceiver);
        unregisterReceiver(netBroadcastReceiver);
    }

    /**
     * 初始化ExpandableListView
     */
    private void initEList(GoodsDetailBean bean) {

        listView.setOnGroupExpandListener(this);

        adapter = new ParentAdapter(mContext, bean, bought);

        listView.setAdapter(adapter);

        adapter.setOnChildTreeViewClickListener(this);

    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
        }
    }

    /**
     * 点击子ExpandableListView的子项时，回调本方法，根据下标获取值来做相应的操作
     */
    @Override
    public void onClickPosition(int parentPosition, int groupPosition,
                                int childPosition) {
        //三级子列表获取的值
        // do something
        String childName = bean.getUnits().get(parentPosition).getUnits()
                .get(groupPosition).getUnits().get(childPosition)
                .getId();
        String type = bean.getUnits().get(parentPosition).getUnits()
                .get(groupPosition).getUnits().get(childPosition)
                .getIs_free();
        //  Toast.makeText(mContext,"子类"+childName, Toast.LENGTH_SHORT).show();

        if (uid == null || uid.equals("")) {//uid为空的时候跳转到登陆
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
            return;
        }
        if (bought && (bean.getExpire_time() == null ||"".equals(bean.getExpire_time())||
                (Long.valueOf(bean.getExpire_time())- (System.currentTimeMillis()/1000)) <= 0)) {
            MAlert.alert("本书已过期，请重新购买");
            bought=false;
            return;
        }
        if ((!type.equals("1")) && (bean.getExpire_time() == null ||"".equals(bean.getExpire_time())||
                (Long.valueOf(bean.getExpire_time())- (System.currentTimeMillis()/1000)) <= 0)) {
            MAlert.alert("该题不是免费");
            return;
        }
        Intent intent = new Intent(this, ZongHeActivity.class);
        intent.putExtra("type", childName);
        startActivity(intent);
    }

    /**
     * 展开一项，关闭其他项，保证每次只能展开一项
     */
    @Override
    public void onGroupExpand(int groupPosition) {
        for (int i = 0; i < bean.getUnits().size(); i++) {
            if (i != groupPosition) {
                listView.collapseGroup(i);
            }
        }
    }

    @Override
    public void update(Observable o, Object arg) {

        ResultEntity entity = handlerError(arg);
        if (entity != null) {
            if (entity.getCode().equals("1111")) {
                Intent intent = new Intent(MyApplication.instance, LoginActivity.class);
                startActivity(intent);
                return;
            }
            if (entity.getEventType() == presenter.GoodsList_success) {
                bean = (GoodsDetailBean) entity.getData();
                initEList(bean);
                if(bought){
                    long validtime = Long.valueOf(bean.getExpire_time());
                    validTime.setText("有效期至:" + new SimpleDateFormat("yyyy年MM月dd日").format(new java.util.Date(validtime * 1000L)));
                }
//                initEList();

            }
            try {
                closeProgressDialog();
            } catch (Exception e) {
            }

        }
    }
}
